import { isIos } from "@/utils";

export const optimizeSafari = () => {
  // -------------------------------------------- 软键盘相关bug解决
  // 点击空白关闭键盘
  const closeKeyboard = (e: Event) => {
    if (e.target != document.activeElement) {
      // @ts-ignore
      document.activeElement?.blur();
    }
  };

  // 软键盘弹出的事件处理
  document.addEventListener("focusin", () => {
    if (isIos) {
      document.addEventListener("touchstart", closeKeyboard);
      // 强制禁用滚动
      // document.addEventListener("touchmove", (e) => e.preventDefault(), {
      //   passive: false,
      // });
    }
  });
  // 软键盘收起的事件处理
  document.addEventListener("focusout", () => {
    if (isIos) {
      window.scrollTo(0, 0);
      setTimeout(() => {
        document.removeEventListener("touchstart", closeKeyboard);
      }, 100);
    }
  });
  // -------------------------------------------- 防止多点触控
  // document.addEventListener(
  //   "touchstart",
  //   function (event) {
  //     if (event.touches.length > 1) {
  //       event.preventDefault();
  //     }
  //   },
  //   { passive: false }
  // );
  // -------------------------------------------- 禁止默认的缩放手势
  document.addEventListener(
    "gesturestart",
    function (event) {
      event.preventDefault();
    },
    { passive: false }
  );
  // -------------------------------------------- 禁用右键菜单
  // document.addEventListener(
  //   "touchstart",
  //   (e) => {
  //     // e.preventDefault();
  //   },
  //   { passive: false }
  // );
  // document.addEventListener(
  //   "touchend",
  //   (e) => {
  //     e.preventDefault();
  //   },
  //   { passive: false }
  // );
  // document.addEventListener(
  //   "touchmove",
  //   (e) => {
  //     e.preventDefault();
  //   },
  //   { passive: false }
  // );
  // document.addEventListener("contextmenu", function (event) {
  //   event.preventDefault();
  // });
};

// 获取安全区
export function getSafeArea(): { top: number; bottom: number } {
  const localSafaArea = localStorage.getItem("safa-area");
  if (localSafaArea) return JSON.parse(localSafaArea);

  const safeAreaTop = getComputedStyle(document.documentElement)
    .getPropertyValue("--sat")
    .replace("px", "");
  const safeAreaBottom = getComputedStyle(document.documentElement)
    .getPropertyValue("--sab")
    .replace("px", "");

  const obj = {
    top: Number(safeAreaTop),
    bottom: Number(safeAreaBottom),
  };

  localStorage.setItem("safa-area", JSON.stringify(obj));

  return obj;
}
